package com.example.huhaichao.fmusic;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.huhaichao.fmusic.adapter.MusicListAdapter;
import com.example.huhaichao.fmusic.model.PropertyBean;
import com.example.huhaichao.fmusic.service.MusicService;
import com.example.huhaichao.fmusic.utils.ControlCode;
import com.example.huhaichao.fmusic.utils.MusicData;
import com.example.huhaichao.fmusic.utils.MusicList;
import com.example.huhaichao.fmusic.utils.Util;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by huhaichao
 * 主activity 通过广播 控制 service 的音乐播放
 */

public class MainActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private RecyclerView recyclerView;
    private MusicListAdapter musicListAdapter;
    private TextView emptyView;//数据库为空
    private int status;//播放器默认状态
    private StatusChangedReceiver receiver;//广播接收器：更新播放器状态
    private int number = 0;//默认播放曲目ID
    private ImageButton previous, play, stop, next;
    private SeekBar music_seekBar;//进度条
    private TextView music_current;//当前播放时间
    private TextView music_duration;//总时长
    private int duration = 0;//当前歌曲总时长
    private int time = 0;//当前歌曲已播放的时长
    private Handler handler;
    private RelativeLayout bg_layout;//背景布局
    private boolean isExit = false;//退出状态
    private int playmode = 0;//默认顺序播放
    private boolean sleepmode = false;//是否启动睡眠模式
    private int sleepminute = 20;//默认睡眠时间
    private Timer timer_sleep;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        status = ControlCode.COMMAND_STOP;
        initdata();
        initView();
        loadTheme();
        setListener();
        bindStatusChangedReceiver();
        initSeekBarHandler();
        startService(new Intent(this, MusicService.class));//启动MusicService，绑定相应的广播
    }

    public void initSeekBarHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case ControlCode.PROGRESS_INCREASE:
                        if (music_seekBar.getProgress() < (duration-1)) {
                            music_seekBar.setProgress(time);
//                            music_seekBar.incrementProgressBy(1000);
                            handler.sendEmptyMessageDelayed(ControlCode.PROGRESS_INCREASE, 1000);
                            music_current.setText(Util.formatTime(time));
                            time += 1000;
                        }
                        break;
                    case ControlCode.PROGRESS_PAUSE:
                        handler.removeMessages(ControlCode.PROGRESS_INCREASE);
                        break;
                    case ControlCode.PROGRESS_RESET:
                        handler.removeMessages(ControlCode.PROGRESS_INCREASE);
                        music_seekBar.setProgress(0);
                        music_current.setText("00:00");
                        break;
                }
            }
        };
    }
    /**
     * 初始化音乐数据
     */
    public void initdata() {
        MusicData musicData = new MusicData(this);
        musicData.initMusicData();
    }

    /**
     * 初始化UI视图
     */
    public void initView() {
        bg_layout = (RelativeLayout) findViewById(R.id.bg_layout);

        music_seekBar = (SeekBar) findViewById(R.id.seekbar);
        music_current = (TextView) findViewById(R.id.current);
        music_duration = (TextView) findViewById(R.id.duration);

        previous = (ImageButton) findViewById(R.id.previous);
        play = (ImageButton) findViewById(R.id.play);
        stop = (ImageButton) findViewById(R.id.stop);
        next = (ImageButton) findViewById(R.id.next);

        emptyView = (TextView) findViewById(R.id.emptyView);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        if (MusicList.getMusicList().isEmpty()) {
            emptyView.setVisibility(View.VISIBLE);
//            recyclerView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            musicListAdapter = new MusicListAdapter();
            recyclerView.setAdapter(musicListAdapter);
        }
    }

    /**
     * 设置监听器
     */
    public void setListener() {
        previous.setOnClickListener(this);
        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        next.setOnClickListener(this);

        musicListAdapter.setOnItemClickListener(new MusicListAdapter.onItemClickListener() {
            @Override
            public void onItemClick(int i) {
                number = i;
                sendBroadcastOnCommand(ControlCode.COMMAND_PLAY);
            }
        });

        music_seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            //进度条停止不动
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.sendEmptyMessage(ControlCode.PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (status != ControlCode.STATUS_STOPPED) {
                    time = seekBar.getProgress();
                    music_current.setText(Util.formatTime(time));
                    sendBroadcastOnCommand(ControlCode.COMMAND_SEEK_TO);
                }
                if (status == ControlCode.STATUS_PLAYING) {
                    sendBroadcastOnCommand(ControlCode.COMMAND_SEEK_TO);
                    handler.sendEmptyMessageDelayed(ControlCode.PROGRESS_INCREASE, 1000);
                }
                if(status==ControlCode.STATUS_PAUSED)
                {
                    sendBroadcastOnCommand(ControlCode.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(ControlCode.COMMAND_RESUME);
                    handler.sendEmptyMessageDelayed(ControlCode.PROGRESS_INCREASE, 1000);
                }
            }
        });

    }

    /**
     * 注册广播接收器
     * 接收 播放器更新 广播
     */
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                ControlCode.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    /**
     * 发送广播：提醒MusicService 执行操作
     * 参数 ：command(操作)
     *        number(曲目ID)
     **/
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(ControlCode.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同命令，封装不同的数据
        switch (command) {
            case ControlCode.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case ControlCode.COMMAND_SEEK_TO:
                intent.putExtra("time", time);
                break;
            case ControlCode.COMMAND_PREVIOUS:
            case ControlCode.COMMAND_NEXT:
            case ControlCode.COMMAND_PAUSE:
            case ControlCode.COMMAND_STOP:
            case ControlCode.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.previous:
                sendBroadcastOnCommand(ControlCode.COMMAND_PREVIOUS);
                break;
            case R.id.play:
                switch (status) {
                    case ControlCode.STATUS_PLAYING:
                        Log.d(TAG, "onClick: 发送的状态："+status);
                        sendBroadcastOnCommand(ControlCode.COMMAND_PAUSE);
                        break;
                    case ControlCode.STATUS_PAUSED:
                        sendBroadcastOnCommand(ControlCode.COMMAND_RESUME);
                        break;
                    case ControlCode.STATUS_STOPPED:
                        Log.d(TAG, "onClick: 发送的状态："+status);
                        sendBroadcastOnCommand(ControlCode.COMMAND_PLAY);
                        break;
                    default:
                        break;
                }
                break;//这里少了break，所以执行了play 和 stop
            case R.id.stop:
                sendBroadcastOnCommand(ControlCode.COMMAND_STOP);
                break;
            case R.id.next:
                sendBroadcastOnCommand(ControlCode.COMMAND_NEXT);
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_theme:
                new AlertDialog.Builder(this, R.style.AlertDialogCustom)
                        .setTitle("选择主题")
                        .setItems(R.array.theme, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                setTheme(which);
                                PropertyBean propertyBean = new PropertyBean(MainActivity.this);
                                propertyBean.saveTheme(Integer.toString(which));
                            }
                        }).show();
                break;
            case R.id.menu_mode:
                String[] s = new String[]{"顺序播放", "列表播放", "单曲循环"};
                AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogCustom);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(s, playmode, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        playmode = which;
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (playmode) {
                            case 0:
                                playmode = ControlCode.MODE_0;
                                Toast.makeText(MainActivity.this, "顺序播放", Toast.LENGTH_LONG).show();
                                break;
                            case 1:
                                playmode = ControlCode.MODE_1;
                                Toast.makeText(MainActivity.this, "列表循环", Toast.LENGTH_LONG).show();
                                break;
                            case 2:
                                playmode = ControlCode.MODE_2;
                                Toast.makeText(MainActivity.this, "单曲循环", Toast.LENGTH_LONG).show();
                                break;
                        }
                    }
                });
                builder.create().show();
                break;
            case R.id.menu_sleep:
                showSleepDialog();
                break;
            case R.id.menu_about:
                Toast.makeText(this, "胡海潮", Toast.LENGTH_LONG).show();
                break;
            case R.id.menu_quit:
                new AlertDialog.Builder(this, R.style.AlertDialogCustom)
                        .setTitle("是否退出?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                System.exit(0);
                            }
                        }).setNegativeButton("取消", null).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcastOnCommand(ControlCode.COMMAND_CHECK_IS_PLAYING);
    }

    @Override
    protected void onDestroy() {
        if (status == ControlCode.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    //设置背景
    public void setTheme(int position) {
        switch (position) {
            case 0:
                bg_layout.setBackgroundResource(R.drawable.bg_0);
                break;
            case 1:
                bg_layout.setBackgroundResource(R.drawable.bg_1);
                break;
        }
    }

    public void loadTheme() {
        PropertyBean propertyBean = new PropertyBean(MainActivity.this);
        String theme = propertyBean.loadTheme();
        setTheme(Integer.parseInt(theme));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit) {
                finish();
            } else {
                Toast.makeText(MainActivity.this, getResources().getString(R.string.press_quit), Toast.LENGTH_SHORT).show();
                isExit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isExit = false;
                    }
                }, 2000);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 睡眠设置
     */
    public void showSleepDialog() {
        View view = this.getLayoutInflater().inflate(R.layout.dialog, null);

        final TextView text = (TextView) view.findViewById(R.id.text);
        Switch mswitch = (Switch) view.findViewById(R.id.mswitch);
        final SeekBar seekBar = (SeekBar) view.findViewById(R.id.seekbar);

        mswitch.setChecked(sleepmode);
        seekBar.setProgress(sleepminute);
        text.setText("睡眠设置：" + sleepminute + " 分");

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                sleepminute = progress;
                text.setText("睡眠设置：" + sleepminute + " 分");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sleepmode = isChecked;
            }
        });

        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.exit(0);
            }
        };

        //定义对话框
        AlertDialog.Builder dialog = new AlertDialog.Builder(this, R.style.AlertDialogCustom);
        dialog.setTitle("睡眠设置");
        dialog.setView(view);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (sleepmode) {
                    timer_sleep = new Timer();
                    int time = seekBar.getProgress();
                    sleepminute=time;
                    timer_sleep.schedule(timerTask, time * 60 * 1000);
                } else {
                    timerTask.cancel();
                    if (timer_sleep != null)
                        timer_sleep.cancel();
                    dialog.dismiss();
                }
            }
        });

        dialog.show();
    }

    /**
     * 接收广播
     * 更新播放器状态
     */
    class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            //获取播放器状态
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case ControlCode.STATUS_PLAYING:
                    String musicName = intent.getStringExtra("musicName");
                    String musicAritist = intent.getStringExtra("musicAritist");
                    handler.removeMessages(ControlCode.PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    Log.d(TAG, "onReceive: number==" + number);
                    music_seekBar.setProgress(time);
                    music_seekBar.setMax(duration);
                    handler.sendEmptyMessageDelayed(ControlCode.PROGRESS_INCREASE, 1000);
                    music_duration.setText(Util.formatTime(duration));
                    play.setBackgroundResource(R.drawable.pause);
                    MainActivity.this.setTitle("正在播放："+musicName+" - "+musicAritist);
                    break;
                case ControlCode.STATUS_PAUSED:
                    handler.sendEmptyMessage(ControlCode.PROGRESS_PAUSE);
                    play.setBackgroundResource(R.drawable.play);
                    String s=MainActivity.this.getTitle().toString().replace("正在播放","已暂停");
                    MainActivity.this.setTitle(s);
                    break;
                case ControlCode.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    music_current.setText(Util.formatTime(time));
                    music_duration.setText(Util.formatTime(duration));
                    handler.sendEmptyMessage(ControlCode.PROGRESS_RESET);
                    play.setBackgroundResource(R.drawable.play);
                    MainActivity.this.setTitle("潮流音乐");
                    break;
                case ControlCode.STATUS_COMPLETED:
                    switch (playmode) {
                        case ControlCode.MODE_0:
                            if (number == MusicList.getMusicList().size() - 1)
                                sendBroadcastOnCommand(ControlCode.STATUS_STOPPED);
                            else
                                sendBroadcastOnCommand(ControlCode.COMMAND_NEXT);
                            break;
                        case ControlCode.MODE_1:
                            if (number == MusicList.getMusicList().size() - 1) {
                                number = 0;
                                sendBroadcastOnCommand(ControlCode.COMMAND_PLAY);
                            } else
                                sendBroadcastOnCommand(ControlCode.COMMAND_NEXT);
                            break;
                        case ControlCode.MODE_2:
                            sendBroadcastOnCommand(ControlCode.COMMAND_PLAY);
                            break;
                    }
//                    //根据播放模式 执行操作
//                    //这里先 默认 下一首
//                    sendBroadcastOnCommand(ControlCode.COMMAND_NEXT);
                    break;
                default:
                    break;
            }
        }
    }
}
